#include "../include/interpolationengine.h"
#include <QtMath>
#include <QDebug>

/**
 * @brief 插值渲染引擎实现
 * 
 * 基于Qt6_Client_Development_Guide.md的指导实现
 * 提供高性能的游戏对象插值渲染
 */

InterpolationEngine::InterpolationEngine(QObject *parent)
    : QObject(parent)
    , m_serverTickInterval(100)  // 默认100ms，匹配服务器
    , m_smoothMovementEnabled(true)
    , m_interpolationStrength(1.0f)
    , m_lastUpdateTime(0)
    , m_currentTime(0)
{
    qDebug() << "InterpolationEngine: 初始化插值渲染引擎";
}

InterpolationEngine::InterpolatedPosition InterpolationEngine::interpolateSnakePosition(
    const SnakeData& current, const SnakeData& previous, float factor)
{
    InterpolatedPosition result;
    
    if (current.body.isEmpty() || previous.body.isEmpty()) {
        // 如果没有足够的数据，返回当前位置
        if (!current.body.isEmpty()) {
            result.x = current.body.first().x();
            result.y = current.body.first().y();
        }
        return result;
    }
    
    // === 插值头部位置 ===
    QPointF currentHead = current.body.first();
    QPointF previousHead = previous.body.first();
    
    if (m_smoothMovementEnabled) {
        // 使用平滑插值
        result.x = smoothLerp(previousHead.x(), currentHead.x(), factor);
        result.y = smoothLerp(previousHead.y(), currentHead.y(), factor);
    } else {
        // 使用线性插值
        result.x = lerp(previousHead.x(), currentHead.x(), factor);
        result.y = lerp(previousHead.y(), currentHead.y(), factor);
    }
    
    // === 插值旋转角度 ===
    float currentAngle = current.direction * 90.0f;  // 0=UP, 1=DOWN, 2=LEFT, 3=RIGHT
    float previousAngle = previous.direction * 90.0f;
    result.rotation = interpolateAngle(previousAngle, currentAngle, factor);
    
    // === 设置缩放和透明度 ===
    result.scale = current.alive ? 1.0f : lerp(1.0f, 0.8f, factor);  // 死亡时缩小
    result.alpha = current.alive ? 1.0f : lerp(1.0f, 0.5f, factor);  // 死亡时变透明
    
    return result;
}

QList<InterpolationEngine::InterpolatedPosition> InterpolationEngine::interpolateSnakeBody(
    const SnakeData& current, const SnakeData& previous, float factor)
{
    QList<InterpolatedPosition> result;
    
    if (current.body.isEmpty()) {
        return result;
    }
    
    // === 处理身体各段 ===
    for (int i = 0; i < current.body.size(); ++i) {
        InterpolatedPosition pos;
        QPointF currentPos = current.body[i];
        
        if (i < previous.body.size() && m_smoothMovementEnabled) {
            // 有对应的前一帧位置，进行插值
            QPointF previousPos = previous.body[i];
            pos.x = smoothLerp(previousPos.x(), currentPos.x(), factor);
            pos.y = smoothLerp(previousPos.y(), currentPos.y(), factor);
        } else {
            // 没有对应位置或禁用平滑移动，直接使用当前位置
            pos.x = currentPos.x();
            pos.y = currentPos.y();
        }
        
        // === 身体段的渐变效果 ===
        float segmentRatio = float(i) / float(current.body.size());
        pos.scale = 1.0f - segmentRatio * 0.1f;  // 从头到尾逐渐变小
        pos.alpha = 1.0f - segmentRatio * 0.2f;  // 从头到尾逐渐变透明
        pos.rotation = 0.0f;  // 身体段不旋转
        
        result.append(pos);
    }
    
    return result;
}

InterpolationEngine::InterpolatedPosition InterpolationEngine::interpolateFoodPosition(
    const FoodData& current, const FoodData& previous, float factor)
{
    InterpolatedPosition result;
    
    // === 食物位置插值（通常食物不移动，但可能有生成动画） ===
    if (m_smoothMovementEnabled) {
        result.x = smoothLerp(previous.position.x(), current.position.x(), factor);
        result.y = smoothLerp(previous.position.y(), current.position.y(), factor);
    } else {
        result.x = current.position.x();
        result.y = current.position.y();
    }
    
    // === 食物动画效果 ===
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    qint64 age = currentTime - current.spawnTime;
    
    // 生成动画：前500ms从小到大
    if (age < 500) {
        float spawnProgress = float(age) / 500.0f;
        result.scale = smoothLerp(0.0f, current.scale, spawnProgress);
        result.alpha = smoothLerp(0.0f, 1.0f, spawnProgress);
    } else {
        result.scale = current.scale;
        result.alpha = 1.0f;
    }
    
    // 旋转动画：缓慢旋转
    result.rotation = fmod(age * 0.1f, 360.0f);
    
    return result;
}

QPointF InterpolationEngine::predictNextPosition(const SnakeData& snake, int deltaMs)
{
    if (snake.body.isEmpty()) {
        return QPointF();
    }
    
    QPointF currentHead = snake.body.first();
    
    // === 根据方向预测下一个位置 ===
    QPointF direction;
    switch (snake.direction) {
    case 0: direction = QPointF(0, -1); break;  // UP
    case 1: direction = QPointF(0, 1); break;   // DOWN
    case 2: direction = QPointF(-1, 0); break;  // LEFT
    case 3: direction = QPointF(1, 0); break;   // RIGHT
    default: direction = QPointF(0, 0); break;
    }
    
    // === 计算预测位置 ===
    float moveProgress = float(deltaMs) / float(m_serverTickInterval);
    QPointF predictedPos = currentHead + direction * moveProgress;
    
    return predictedPos;
}

float InterpolationEngine::calculateInterpolationFactor(
    qint64 currentTime, qint64 lastUpdateTime, int serverTickInterval)
{
    if (lastUpdateTime == 0 || serverTickInterval <= 0) {
        return 1.0f;  // 没有历史数据，使用当前状态
    }
    
    qint64 timeSinceUpdate = currentTime - lastUpdateTime;
    float factor = float(timeSinceUpdate) / float(serverTickInterval);
    
    // === 限制插值因子范围 ===
    factor = qBound(0.0f, factor, 1.0f);
    
    // === 应用插值强度 ===
    factor *= m_interpolationStrength;
    
    return factor;
}

void InterpolationEngine::updateGameState(
    const QList<SnakeData>& snakes, const QList<FoodData>& foods, qint64 timestamp)
{
    QMutexLocker locker(&m_stateMutex);
    
    // === 保存上一帧状态 ===
    m_previousSnakes = m_currentSnakes;
    m_previousFoods = m_currentFoods;
    
    // === 更新当前状态 ===
    m_currentSnakes = snakes;
    m_currentFoods = foods;
    
    // === 更新时间戳 ===
    m_lastUpdateTime = m_currentTime;
    m_currentTime = timestamp;
    
    emit interpolationUpdated();
}

void InterpolationEngine::reset()
{
    QMutexLocker locker(&m_stateMutex);
    
    qDebug() << "InterpolationEngine: 重置插值引擎";
    
    m_currentSnakes.clear();
    m_previousSnakes.clear();
    m_currentFoods.clear();
    m_previousFoods.clear();
    
    m_lastUpdateTime = 0;
    m_currentTime = 0;
}

// === 私有插值算法实现 ===

float InterpolationEngine::lerp(float a, float b, float t)
{
    return a + (b - a) * t;
}

float InterpolationEngine::smoothLerp(float a, float b, float t)
{
    // 使用平滑步函数（smoothstep）
    t = t * t * (3.0f - 2.0f * t);
    return lerp(a, b, t);
}

float InterpolationEngine::interpolateAngle(float from, float to, float t)
{
    // === 处理角度环绕 ===
    float diff = to - from;
    
    // 确保使用最短路径
    if (diff > 180.0f) {
        diff -= 360.0f;
    } else if (diff < -180.0f) {
        diff += 360.0f;
    }
    
    float result = from + diff * t;
    
    // 标准化角度到 [0, 360) 范围
    while (result < 0.0f) result += 360.0f;
    while (result >= 360.0f) result -= 360.0f;
    
    return result;
}

QPointF InterpolationEngine::interpolatePosition(const QPointF& from, const QPointF& to, float t)
{
    if (m_smoothMovementEnabled) {
        return QPointF(
            smoothLerp(from.x(), to.x(), t),
            smoothLerp(from.y(), to.y(), t)
        );
    } else {
        return QPointF(
            lerp(from.x(), to.x(), t),
            lerp(from.y(), to.y(), t)
        );
    }
}
